package org.example.system.controller;


import cn.hutool.core.util.IdUtil;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.example.system.common.result.Result;
import org.example.system.model.dto.RefundRequestDto;
import org.example.system.model.form.RefundForm;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@Tag(name = "退款记录接口")
@RestController
@RequestMapping("/api/v1/wx/refund")
public class RefundRecordController {

    private final WxPayService wxPayService;

    public RefundRecordController(WxPayService wxPayService) {
        this.wxPayService = wxPayService;
    }


    @PostMapping("/applyRefund")
    public Result applyRefund1(@RequestBody RefundForm refundForm) {
        try {
            // 校验 refundForm 是否提供了商户订单号
            if (StringUtils.isBlank(refundForm.getOutTradeNo())) {
                return Result.failed("商户订单号[outTradeNo]必须提供");
            }

            // 生成唯一的退款单号 (outRefundNo) 使用雪花算法
            String outRefundNo = IdUtil.getSnowflake(1, 1).nextIdStr(); // 1, 1 是机器ID和数据中心ID，可以根据实际情况修改

            // 构建退款请求参数
            WxPayRefundRequest refundRequest = WxPayRefundRequest.newBuilder()
                    .outTradeNo(refundForm.getOutTradeNo())  // 商户订单号
                    .outRefundNo(outRefundNo)  // 生成的退款单号
                    .refundDesc(refundForm.getRefundDesc())  // 退款描述
                    .totalFee(refundForm.getTotalFee().multiply(BigDecimal.valueOf(100)).intValue()) // 转换为分
                    .refundFee(refundForm.getTotalFee().multiply(BigDecimal.valueOf(100)).intValue())  // 退款金额
                    .build();

            // 调用微信退款接口
            WxPayRefundResult result = wxPayService.refund(refundRequest);

            // 返回退款结果
            if ("SUCCESS".equals(result.getReturnCode()) && "SUCCESS".equals(result.getResultCode())) {
                return Result.success(result);
            } else {
                return Result.failed("退款申请失败：" + result.getErrCodeDes());
            }
        } catch (Exception e) {
            return Result.failed("退款处理异常：" + e.getMessage());
        }
    }



}
